//
//  AlreadyBoughtGoodsViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/18.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "AlreadyBoughtGoodsViewController.h"
#import "AlreadyBoughtCell.h"

#import "CommentViewController.h"
#import "commentsCell.h"
#import "BaseUrlConfig.h"
#import "BannerCell.h"
#import "ShareUserModel.h"
#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"
#import "GetRemandModle.h"
#import "ShangPinListModel.h"
#import "PurchaseCarModel.h"
#import "MJRefresh.h"
#import "getOrdersModel.h"

@interface AlreadyBoughtGoodsViewController ()
{
    NSInteger currentNum;
    BOOL request;
    NSInteger  pageNum;
    
}
@end

@implementation AlreadyBoughtGoodsViewController
-(void)viewDidAppear:(BOOL)animated
{
    if (request) {
        request = NO;

        ShareUserModel * userUpdate = [ShareUserModel shareUserModel];

        self.labNameText.text=  [NSString stringWithFormat:@"欢迎%@登录",userUpdate.user.userName];

        if (userUpdate.user.photoUrl.length!=0) {

            NSLog(@"%@",[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",hostUserImage,userUpdate.user.photoUrl]]);


            [_imageHead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",hostUserImage,userUpdate.user.photoUrl]] placeholderImage:[UIImage imageNamed:@"我的默认头像"]];

        }
        else
        {
            [self.imageHead setImage:[UIImage imageNamed:@"我的默认头像"]];
            
            
        }
        

        [self getOrdersActionActionRequest];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    currentNum = 0;
        
      pageNum = 10;
    request = YES;
    [_v_Top.lalTitel setText:@"已购商品"];
    
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
     
    self.textView.delegate  = self;
    
    [_btnSure removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnSure addTarget:self action:@selector(btnSureAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_btnCancle removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnCancle addTarget:self action:@selector(btnCancleAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    [_btnGoodComment removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnGoodComment addTarget:self action:@selector(btnGoodOrBadCommentAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_btnBadComment removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnBadComment addTarget:self action:@selector(btnGoodOrBadCommentAction:) forControlEvents:UIControlEventTouchUpInside];
    UINib *nibCell = [UINib nibWithNibName:NSStringFromClass([AlreadyBoughtCell class]) bundle:nil];
    [self.tableView registerNib:nibCell forCellReuseIdentifier:[NSString stringWithFormat:@"%@", [AlreadyBoughtCell class]]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    _viewComment.hidden = YES;
    
    _arrData = [[NSMutableArray alloc] init];
    [self setupRefresh];
    // Do any additional setup after loading the view from its nib.
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    
    [self selfViewAutomaticChangeLocationForView:textView];




}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];

}

    //键盘挡住
-(void)selfViewAutomaticChangeLocationForView:(UITextView *)textView{
    
    UITextPosition * pos=[textView.selectedTextRange valueForKey:@"start"];
    CGRect cursorRect = [textView caretRectForPosition:pos];
    
    CGRect rect = [self.view convertRect:cursorRect fromView:textView];
    if (CGRectGetMaxY(rect)>(self.view.frame.size.height-266*2/2)) {
        [UIView animateWithDuration:0.2 animations:^{
            self.view.frame = CGRectMake(self.view.frame.origin.x, -(CGRectGetMaxY(rect)-(self.view.frame.size.height-216*2)), self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
        {
        
        [textView resignFirstResponder];
        [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
        
        [UIView animateWithDuration:0.2 animations:^{
            self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
        }];

        return NO;
        
        }
    
    return YES;
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];
}
#pragma mark - standard tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
        // Return the number of sections.
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return 120;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([_arrData count])
        {
        return [_arrData count];
        }
    else
        {
        return 0;
        }
    
    
}


#pragma mark - Standard TableView delegates
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * identifier = @"AlreadyBoughtCell";
    AlreadyBoughtCell * Cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    Cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    
    [Cell.btnGoComment removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [Cell.btnGoComment addTarget:self action:@selector(btnGoComment:) forControlEvents:UIControlEventTouchUpInside];

    if ([_arrData count]!=0) {


        getOrdersModel * modeltemp  = [_arrData objectAtIndex:indexPath.row];

            Cell.btnGoComment.tag  = indexPath.row;
        if (modeltemp.orderCommodity.count!=0) {
            Cell.labProdectName.text = [[modeltemp.orderCommodity objectAtIndex:0] objectForKey:@"name"];
            [Cell.imageProdect sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,[[modeltemp.orderCommodity objectAtIndex:0] objectForKey:@"photoUrl"]]]];
            Cell.labXx.text = [NSString stringWithFormat:@"%@X", [[modeltemp.orderCommodity objectAtIndex:0] objectForKey:@"commodityNo"]];

            Cell.labPrce.text = [NSString stringWithFormat:@"¥%@",[[modeltemp.orderCommodity objectAtIndex:0] objectForKey:@"price"]];

        }


        Cell.labTime.text = modeltemp.buyTime;
        
        
    }

        //        [Cell.imaegProdect sd_setImageWithURL:[NSURL URLWithString:] placeholderImage:[UIImage imageNamed:@"SDWebImageDefault"]];
    
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
        //    InDeliveryTabCell * cell =  (InDeliveryTabCell *)[tableView cellForRowAtIndexPath:indexPath];
        //    cell.contentView.backgroundColor = [UIColor clearColor];
        //
        //
        //    ProdectDetailViewController * detail  = [[ProdectDetailViewController alloc] initWithNibName:@"ProdectDetailViewController" bundle:nil  ];
        //
        //    [self.navigationController pushViewController:detail animated:YES ];
    
    
    
}
- (void)deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated
{
    
        //    InDeliveryTabCell * cell =  (InDeliveryTabCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        //    cell.contentView.backgroundColor = [UIColor clearColor];
    
    
    
}
-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return YES;
}

- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}


-(void)btnGoComment:(UIButton * ) GoComment
{

    self.btnSure.tag  = GoComment.tag;

    
    self.viewComment.hidden = NO;
    
}
-(void)btnSureAction:(UIButton * )SureAction
{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];
    self.viewComment.hidden = YES;
    getOrdersModel * model = nil;
    if ([_arrData count]!=0) {
        model  = [_arrData objectAtIndex:self.btnSure.tag];

    }


    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];


    NSDictionary * params = @{
                              @"evaluateContent":[NSString stringWithFormat:@"%@",self.textView.text],

                              @"evaluateLevel":[NSString stringWithFormat:@"%@",self.evaluateLevel],
                              @"commodityId":[NSString stringWithFormat:@"%@",[[model.orderCommodity objectAtIndex:0] objectForKey:@"commodityId"]],
                              @"orderId":[NSString stringWithFormat:@"%@",[[model.orderCommodity objectAtIndex:0] objectForKey:@"commodityId"]],
                              @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                              @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId],
                              @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id]
                              
                              };
    
    

    [self GoCommentActionActionRequest:params];


    
}

-(void) btnCancleAction:(UIButton * )CancleAction
{
    [[[UIApplication sharedApplication]keyWindow]endEditing:YES];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width,self.view.frame.size.height);
    }];
    
    self.viewComment.hidden = YES;

}

-(void)btnGoodOrBadCommentAction:(UIButton * )GoodCommentAction
{
    
    if (GoodCommentAction == self.btnGoodComment) {
        [self.imageGoodComment setImage:[UIImage imageNamed:@"check_choise"]];
        [self.imageBadComment setImage:[UIImage imageNamed:@"check_unchoise"]];
        self.evaluateLevel = @"5";

    }
    else if (GoodCommentAction == self.btnBadComment) {
            [self.imageBadComment setImage:[UIImage imageNamed:@"check_choise"]];
            [self.imageGoodComment setImage:[UIImage imageNamed:@"check_unchoise"]];
        self.evaluateLevel = @"0";

    }

}




#pragma mark - network request getOrdersAction

-(void)getOrdersActionActionRequest

{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,getOrdersAction];
    
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];

    
    NSDictionary * params = @{
                              
                              @"orderStatus":[NSString stringWithFormat:@"%@",@"1"],
                              @"currentNum":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:currentNum]],
                              @"pageNum":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:pageNum]],
                              @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                              @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId],
                              @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id]
    
                              };
    
    
    
    
    
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
     
     
         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     
     NSDictionary * dicRespon = responseObject;
     [self getOrdersActionSuccessWith:dicRespon];
     
     
     
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     [[NetWarningView sharedNetWarningView] show];  //警告网络异常
                                                    //              NSData *doubi = operation.error    ;
                                                    //                  //     JSON格式的NSString转换成NSMutableDictionary
                                                    //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
                                                    //
                                                    //              NSError *err = nil;
                                                    //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObject9WithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     NSLog(@"Error: %@", error);
     NSLog(@"请求出错了: - %@ \n%@",
           [error localizedDescription],
           [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];
    
}

-(void)getOrdersActionSuccessWith :(NSDictionary *)dicRespon
{
    
    
    
    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
        {

            NSArray *arrBussi = [dicRespon objectForKey:@"arr"];
        if (arrBussi.count==0) {
            
            currentNum  = 0 ;
            
            
            pageNum = 10 ;
            
            
        }
            if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
            {
            [_arrData removeAllObjects];

                for (NSDictionary *dicTmp in arrBussi)
                {
                    NSError *error = nil;
                    getOrdersModel *modelTmp =
                    [MTLJSONAdapter modelOfClass:[getOrdersModel class] fromJSONDictionary:dicTmp error:&error];
                    if(error == nil)
                    {
                        [_arrData addObject:modelTmp];
                    }
                }

            }
            [self.tableView reloadData];
        
        
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        
        }
    else
        {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        }
    
}



#pragma mark - network request evaluation_commodityAction

-(void)GoCommentActionActionRequest:(NSDictionary * )params

{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,evaluation_commodityAction];





    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self GoCommentSuccessWith:dicRespon];



         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObject9WithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)GoCommentSuccessWith :(NSDictionary *)dicRespon
{



    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {

        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

    }

}



#pragma mark 集成刷新控件
- (void)setupRefresh
{
    
        // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
        // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = headerPullToRefreshTextkey;
    self.tableView.headerReleaseToRefreshText  = headerReleaseToRefreshTextkey;
    self.tableView.headerRefreshingText = headerRefreshingTextKey;
    
        // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    self.tableView.footerPullToRefreshText = footerPullToRefreshTextKey;
    self.tableView.footerReleaseToRefreshText =footerPullToRefreshTextKey;
    self.tableView.footerRefreshingText = footerRefreshingTextKey;
    
}

-(void)headerRereshing{
    
    currentNum  = pageNum;
    
    
    pageNum = currentNum + pageNum ;
    NSLog(@"--------%d-----\n--------%d",currentNum,pageNum);
    
    
    
    [self getOrdersActionActionRequest];
    
    
    [self.tableView headerEndRefreshing];
    
}

-(void)footerRereshing{
    
    currentNum  = pageNum;
    
    
    pageNum = currentNum + pageNum ;
    
    
    NSLog(@"--------%d-----\n--------%d",currentNum,pageNum);
    
    
    
    [self getOrdersActionActionRequest];
    [self.tableView footerEndRefreshing];
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
